<template>
  <el-input v-model="wValue" v-bind="$attrs" v-on="$listeners" class="w-number-input" @blur="onBlur">
    <span v-show="unit" slot="suffix">{{ unit }}</span>
  </el-input>
</template>

<script>
export default {
  name: 'WNumberInput',
  props: {
    value: {
      type: [Number, String]
    },
    // 是否为大数
    bigInt: {
      type: Boolean,
      default: false
    },
    // 单位
    unit: {
      type: String,
      default: ''
    },
    // 精度
    precision: {
      type: Number
    },
    min: {
      type: Number
    },
    max: {
      type: Number
    }
  },
  data() {
    return {
      wValue: '',
      lastValidValue: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.wValue = val
      }
    }
  },
  methods: {
    onValid() {
      const value = this.value

      if (isNaN(value)) {
        return this.lastValidValue
      } else {
        this.lastValidValue = Number(value)
        return Number(value)
      }
    },
    onEdge(value) {
      if (value < this.min) {
        return this.min
      } else if (value > this.max) {
        return this.max
      }
      return value
    },
    // 处理精度
    onPrecision(value) {
      const precision = this.precision

      if (precision === 0) {
        return parseInt(value)
      }
      return Number(Number(value).toFixed(precision))
    },
    onBlur() {
      let numberVal = this.onValid()

      numberVal = this.onEdge(numberVal)

      if (this.precision >= 0) {
        numberVal = this.onPrecision(numberVal)
      }

      this.$emit('input', numberVal)
    }
  }
}
</script>

<style lang="scss">
.w-number-input {
  .el-input__suffix {
    display: flex;
    align-items: center;
    right: 10px;
  }
}
</style>
